<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/23
 * Time: 14:52
 */

namespace osc\admin\controller;

use osc\common\controller\AdminBase;
use think\Db;
use think\Request;
use osc\common\service\Excel;

class Change extends AdminBase
{

    protected function _initialize(){
        parent::_initialize();
        $this->assign('breadcrumb1','兑换操作');
        $this->assign('breadcrumb4','元宝兑换记录');
        $this->assign('breadcrumb6','元宝兑换');
    }

    public function add()
    {
       

        if(request()->isGet())
        {
             $token=input('param.token');

              $info = Db::name('jilin_ticket')->where('token', $token)->find();
              $this->assign('info',$info);
        }

        if(request()->isPost()){
            $data = input('post.');
            $info = Db::name('jilin_ticket')->where('token',$data['token'])->find();
            //查询发行价
            $issue = Db::name('contract_issue')->where('variety_id',$info['variety_id'])->find();
            //var_dump($info);
            $dt['num'] = $info['num'] + $data['num'];
            $dt['money'] = ceil(($info['num'] + $data['num']) * ($info['issue'] - $issue['issue']));
            $total_use = ceil($data['num'] * ($info['issue'] - $issue['issue']));

            $user = Db::name('member')->where('username',$info['username'])->find();

            if($data['num']<=0 )
            {
                $this->error('输入的数量不正确');
            }


            if($user['jilin_bean'] < $total_use )
            {
                $this->error('用户可用元宝不够');
            }

            Db::name('jilin_ticket')->where('token',$info['token'])->update($dt);

            Db::name('member')->where('username',$info['username'])->setDec('jilin_bean',$total_use);
            $info = Db::name('jilin_ticket')->where('token',$info['token'])->find();
            $this->success('修改成功');
            $this->assign('info',$info);

        }
        $this->assign('crumbs','修改');
        $this->assign('breadcrumb1','元宝兑换');
        $this->assign('breadcrumb2','元宝兑换'); 
        return $this->fetch();
    }

    public function dec()
    {
        if(request()->isGet())
        {
             $token=input('param.token');

              $info = Db::name('jilin_ticket')->where('token', $token)->find();
              $this->assign('info',$info);
        }

        if(request()->isPost()){


            $data = input('post.');
            $info = Db::name('jilin_ticket')->where('token',$data['token'])->find();
            //查询发行价
            $issue = Db::name('contract_issue')->where('variety_id',$info['variety_id'])->find();
            if($data['num']>=$info['num'])
            {
                $this->error('输入的数量不能大于等于申请的数量');
            }
            //var_dump($info);
            $dt['num'] = $info['num'] - $data['num'];
            $dt['money'] = ceil(($info['num'] - $data['num']) * ($info['issue'] - $issue['issue']));
            $total_use = ceil($data['num'] * ($info['issue'] - $issue['issue']));




            Db::name('jilin_ticket')->where('token',$info['token'])->update($dt);

            Db::name('member')->where('username',$info['username'])->setInc('jilin_bean',$total_use);
            $info = Db::name('jilin_ticket')->where('token',$info['token'])->find();
            $this->success('修改成功');
            $this->assign('info',$info);

        }
        $this->assign('crumbs','修改');
        $this->assign('breadcrumb1','元宝兑换');
        $this->assign('breadcrumb2','元宝兑换');    
        return $this->fetch();
    }


    /**
     * 元宝兑换
     * @return mixed
     */
    public function jilin(){
        $param=input('param.');
        if(!empty($param['username'])){
            $map['username'] = ['like',"%".$param['username']."%"];
        }
        if(!empty($param['first_time'])){
            $map["DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d')"] = $param['first_time'];

        }

        $map['state'] = 0;
//        echo'<pre>';print_r($map);exit;
        $list = Db::name('jilin_ticket')
            ->where($map)
            ->order('create_time desc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);

        $page = $list->render();

        $num = Db::name('jilin_ticket')->where($map)->sum('num');
        $money = Db::name('jilin_ticket')->where($map)->sum('money');
        $this->assign('num',$num);
        $this->assign('money',$money);
        $this->assign('list',$list);
        $this->assign('page',$page);
        return $this->fetch();
    }


    /**
     * 元宝换票批量审批
     * @throws \Exception
     */
    public function jilin_batch(){
        $data = $this->request->param();
        if(!$data){ $this->error('未传值','Change/jilin'); }

        $map = [];
        foreach($data as $key=>$value){
            //获取当前的换票信息
            $ticket = Db::name('jilin_ticket')->where('token',$value)->find();

            $map[$key] = [
                'token'     => $value,
                'state'     => 1,
                'description'		=> '换购了'.$ticket['num'].'枚'.get_variety_name($ticket['variety_id']),
            ];

        }

        $change = new \osc\admin\model\JilinTicket();
        $res = $change->saveAll($map);
        if($res){
            $this->redirect('Change/jilin');
        }else{
            $this->error('审批失败');
        }
    }


    /**
     * 元宝兑换记录
     * @return mixed
     */
    public function jilin_record(){
        $param=input('param.');

        $map = [];
        if(!empty($param['username'])){
            $map['username'] = ['like',"%".$param['username']."%"];
        }
        if(!empty($param['first_time'])){
            $map["DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d')"] = $param['first_time'];

        }
//        echo'<pre>';print_r($map);exit;
        $list = Db::name('jilin_ticket')
            ->where($map)
            ->where('state<>0')
            ->order('create_time desc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);
        $sum = Db::name('jilin_ticket')
            ->where($map)
            ->where('state',1)
            ->sum('money');

        $page = $list->render();
        $this->assign('sum',$sum);
        $this->assign('list',$list);
        $this->assign('page',$page);
        return $this->fetch();
    }


    /**
     * 元宝兑换审核打回
     */
    public function jilin_repulse(){
        $token = $this->request->param('token');

        $change = Db::name('jilin_ticket')->where('token',$token)->find();

        //回复用户金豆数
        $red = Db::name('member')->where('username',$change['username'])->setInc('jilin_bean',$change['money']);

        $res = Db::name('jilin_ticket')->where('token',$token)->update(['state'=>2]);

        if($res && $red){
            $this->redirect('change/jilin');
        }else{
            $this->error('打回失败');
        }
    }


    /**
     * 导出元宝兑换
     * @throws \think\Exception
     */
    public function export_jilin()
    {
        $param=input('param.');
        if(!empty($param['username'])){
            $map['a.username'] = ['like',"%".$param['username']."%"];
        }
        if(!empty($param['first_time'])){
            $map["DATE_FORMAT(FROM_UNIXTIME(a.create_time),'%Y-%m-%d')"] = $param['first_time'];

        }
        $map['a.state'] = 0;
//        echo'<pre>';print_r($map);exit;
        $excel=new Excel();

        $field = [
            "b.idcardname"      =>"账号名称",
            "a.username"        =>"电话号码",
            "c.trade_id"        =>"交易主账号",
            "c.sub_trade_id"    =>"交易副账号",
            "a.exchange_id"     =>"交易所",
            "a.variety_id"      =>"交易品种",
            "sum(a.num)"        =>"换购枚数",
            "a.money"           =>"换购金额",
            "a.issue"           =>"发行价",
            "a.create_time"     =>"提交时间"
        ];

        $list = Db::name('jilin_ticket a,osc_member b,osc_exchange_trade_acc c')
            ->where($map)
            ->where('a.username=b.username and a.username=c.username and a.exchange_id=c.exchange_id')
            ->order('create_time desc')
            ->group('a.username,a.variety_id')
            ->field($field)
            ->select();
        foreach($list as $key=>&$value){
            $value['交易所'] = get_trade_name($value['交易所']);
            $value['交易品种'] = get_variety_name($value['交易品种']);
            $value['提交时间'] = date('Y/m/d',$value['提交时间']);
        }
        $ft = "元宝兑换".date("Y-m-d",time());
//        echo"<pre>";print_r($list);
//        echo"<pre>";print_r($field);exit;
        $excel->setExcelName($ft)
            ->createSheetByList("元宝兑换",$list,$field)
            ->downloadExcel();
    }

}